package com.rc.evcharger.service.market;

import com.rc.evcharger.common.constant.level.UserLevelConstant;
import com.rc.evcharger.component.UidGenerator;
import com.rc.evcharger.mapper.market.MarketActivityMapper;
import com.rc.evcharger.mapper.market.MarketActivityRecordMapper;
import com.rc.evcharger.mapper.ticket.MemberTicketMapper;
import com.rc.evcharger.mapper.ticket.TenantTicketTypeMapper;
import com.rc.evcharger.model.market.MarketActivity;
import com.rc.evcharger.model.market.MarketActivityMember;
import com.rc.evcharger.model.market.MarketActivityMemberExample;
import com.rc.evcharger.model.market.MarketActivityRecord;
import com.rc.evcharger.model.order.OrderDiscountRecord;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.model.ticket.MemberTicket;
import com.rc.evcharger.model.ticket.TenantTicketType;
import com.rc.evcharger.vo.cost.UserLevelPriceResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yang
 * @Date: 2022/7/28 22:39
 */
@Service
public class MarketActivityServiceImpl implements MarketActivityService {

    @Autowired
    private MarketActivityMapper marketActivityMapper;

    @Autowired
    private MarketActivityRecordMapper marketActivityRecordMapper;

    @Autowired
    private TenantTicketTypeMapper ticketTypeMapper;

    @Autowired
    private MemberTicketMapper memberTicketMapper;

    @Autowired
    private MarketActivityMemberService marketActivityMemberService;

    @Autowired
    private UidGenerator uidGenerator;

    @Override
    public MarketActivityMapper getMapper() {
        return marketActivityMapper;
    }

    /**
     * 满减活动
     *
     * @param orderInfo
     * @return
     */
    @Override
    public UserLevelPriceResult updateMarketActivityByOrderInfo(OrderInfo orderInfo) {

        UserLevelPriceResult userLevelPriceResult = UserLevelPriceResult.emptyResult();
        List<OrderDiscountRecord> orderDiscountRecords0 = new ArrayList<>();
        List<MarketActivity> marketActivities0 = new ArrayList<>();
        List<MarketActivityMember> marketActivityMembers = new ArrayList<>();

        if (orderInfo.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return userLevelPriceResult;
        }


        BigDecimal payAmount = orderInfo.getPayAmount();
        BigDecimal discountAmount = orderInfo.getDiscountAmount();

        //查询会员是否参活动 活动类型 0 新用户注册优惠 1 充值送活动默认 2领取活动 3满减 4满返 5拉新  默认1充值
        List<MarketActivityMember> marketActivityMembers1 = marketActivityMemberService.selectByMemberId(orderInfo.getMemberId(), "3");
        if (CollectionUtils.isEmpty(marketActivityMembers1)) {
            return userLevelPriceResult;
        }
        List<Long> list = marketActivityMembers1.stream().map(MarketActivityMember::getMarketActivityId).collect(Collectors.toList());

        List<MarketActivityRecord> marketActivityRecords = marketActivityRecordMapper.listMarketActivity(orderInfo.getPayAmount(), list);
        for (MarketActivityRecord marketActivityRecord : marketActivityRecords) {

            MarketActivity marketActivity = marketActivityRecord.getJoinMarketActivity();
            //0全部 1部分
            if ("1".equals(marketActivity.getActivityScope())) {
                int process = 0;

                //判断是否包含有效站点
                if (StringUtils.isEmpty(marketActivity.getStationIds()) || ",".equals(marketActivity.getStationIds())) {
                    //如果站点ID是空则不处理
                } else {
                    String[] elecStationS = marketActivity.getStationIds().split(",");
                    for (String s : elecStationS) {
                        if (s.equals(String.valueOf(orderInfo.getElecStationId()))) {
                            process += 1;
                            break;
                        }
                    }

                }

                //判断是否包含有效用户
                if (StringUtils.isEmpty(marketActivity.getParticipateUser()) || ",".equals(marketActivity.getParticipateUser())) {
                    //如果用户ID是空则不处理
                } else {
                    String[] memberIds = marketActivity.getParticipateUser().split(",");
                    for (String s : memberIds) {
                        if (s.equals(String.valueOf(orderInfo.getMemberId()))) {
                            process += 1;
                            break;
                        }
                    }

                }

                //无有效数据返回，否则新增活动立减
                if (process == 0) {
                    continue;
                }
            }

            BigDecimal orderAmount = new BigDecimal(marketActivityRecord.getOrderAmount());
            if (payAmount.compareTo(orderAmount) < 0) {
                continue;
            }

            OrderDiscountRecord orderDiscountRecord = new OrderDiscountRecord();
            orderDiscountRecord.setTenantCode(orderInfo.getTenantCode());
            orderDiscountRecord.setOrderId(orderInfo.getOrderId());
            orderDiscountRecord.setCreatedTime(new Date());
            orderDiscountRecord.setDiscountNum(uidGenerator.genDiscountOrderNum("Y")); //优惠券号码
            orderDiscountRecord.setDiscountId(marketActivity.getMarketActivityId());
            orderDiscountRecord.setDiscountType(UserLevelConstant.RC_MARKET_ACTIVITY_SUB + "");
            orderDiscountRecord.setDiscountName("活动满减:" + marketActivity.getActivityName());

            orderDiscountRecords0.add(orderDiscountRecord);

            //计算实付与优惠金额
            BigDecimal awardAmount = new BigDecimal(marketActivityRecord.getAwardAmount());
            if (awardAmount.compareTo(payAmount) == 1) {
                payAmount = BigDecimal.ZERO;
                discountAmount = discountAmount.add(payAmount);
            } else {
                payAmount = payAmount.subtract(awardAmount);
                discountAmount = discountAmount.add(awardAmount);
            }

            //活动进行最大次数
            marketActivity.setLastUpdatedTime(new Date());
            marketActivity.setMaxActivityCount(marketActivity.getMaxActivityCount() + 1);
            marketActivities0.add(marketActivity);

            //用户参与活动累积+1
            MarketActivityMemberExample example = new MarketActivityMemberExample();
            example.createCriteria().andMarketActivityIdEqualTo(marketActivity.getMarketActivityId())
                    .andMemberIdEqualTo(orderInfo.getMemberId());
            List<MarketActivityMember> marketActivityMembers2 = marketActivityMemberService.selectByExample(example);
            MarketActivityMember marketActivityMember1 = marketActivityMembers2.get(0);
            marketActivityMember1.setLastUpdatedTime(new Date());
            marketActivityMember1.setGainCount(marketActivityMember1.getGainCount() + 1);

            marketActivityMembers.add(marketActivityMember1);
//            MarketActivityMember marketActivityMember = marketActivityMemberService.insertByOrderInfoAndMarketActivity(orderInfo, marketActivityRecord);

        }

        //更新订单实付金额与优惠金额
        orderInfo.setPayAmount(payAmount);
        orderInfo.setDiscountAmount(discountAmount);

        //打包
        userLevelPriceResult.setOrderDiscountRecords(orderDiscountRecords0);
        userLevelPriceResult.setMarketActivities(marketActivities0);
        userLevelPriceResult.setMarketActivityMembers(marketActivityMembers);

        return userLevelPriceResult;
    }

    /**
     * 满返活动
     *
     * @param orderInfo
     */
    @Override
    public void insertTicketTypeByMarketActivity(OrderInfo orderInfo) {

        if (orderInfo.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        //查询会员是否参活动 活动类型 0 新用户注册优惠 1 充值送活动默认 2领取活动 3满减 4满返 5拉新  默认1充值
        List<MarketActivityMember> marketActivityMembers = marketActivityMemberService.selectByMemberId(orderInfo.getMemberId(), "4");
        if (CollectionUtils.isEmpty(marketActivityMembers)) {
            return;
        }
        List<Long> list = marketActivityMembers.stream().map(MarketActivityMember::getMarketActivityId).collect(Collectors.toList());


        List<MarketActivityRecord> marketActivityRecords = marketActivityRecordMapper.listMarketActivityAndTicketType(orderInfo.getPayAmount(), list);
        for (MarketActivityRecord marketActivityRecord : marketActivityRecords) {
            MarketActivity marketActivity = marketActivityRecord.getJoinMarketActivity();
            //0全部 1部分
            if ("1".equals(marketActivity.getActivityScope())) {
                int process = 0;

                //判断是否包含有效站点
                if (StringUtils.isEmpty(marketActivity.getStationIds()) || ",".equals(marketActivity.getStationIds())) {
                    //如果站点ID是空则不处理
                } else {
                    String[] elecStationS = marketActivity.getStationIds().split(",");
                    for (String s : elecStationS) {
                        if (s.equals(String.valueOf(orderInfo.getElecStationId()))) {
                            process += 1;
                            break;
                        }
                    }

                }

                //判断是否包含有效用户
                if (StringUtils.isEmpty(marketActivity.getParticipateUser()) || ",".equals(marketActivity.getParticipateUser())) {
                    //如果用户ID是空则不处理
                } else {
                    String[] memberIds = marketActivity.getParticipateUser().split(",");
                    for (String s : memberIds) {
                        if (s.equals(String.valueOf(orderInfo.getMemberId()))) {
                            process += 1;
                            break;
                        }
                    }

                }

                //无有效数据返回，否则新增活动立减
                if (process == 0) {
                    continue;
                }
            }

            //得到有效优惠券
            TenantTicketType ticketType = ticketTypeMapper.selectByPrimaryKey(marketActivityRecord.getTicketTypeId());
            if (ticketType == null) {
                return;
            }
            if ("1".equals(ticketType.getStatus())) {
                continue;
            }

            ticketType.setRemainTicket(ticketType.getRemainTicket() - 1);
            ticketType.setTotalTicket(ticketType.getTotalTicket() + 1);
            //更新优惠券发送数量与剩余数量
            ticketTypeMapper.updateByPrimaryKeySelective(ticketType);

            Calendar calendar = Calendar.getInstance();

            //发送优惠券
            MemberTicket memberTicket = new MemberTicket();
            memberTicket.setMemberId(orderInfo.getMemberId());
            memberTicket.setTicketTypeId(ticketType.getTicketTypeId());
            memberTicket.setGainTime(new Date());
            if ("0".equals(ticketType.getEffectType())) {
                calendar.add(Calendar.DAY_OF_MONTH, ticketType.getEffectDay());
                memberTicket.setEndTime(calendar.getTime());
            } else {
                memberTicket.setEndTime(ticketType.getEffectEndDate());
            }
            memberTicket.setStatus("0");
            memberTicket.setTicketSource("0");
            memberTicket.setCreatedTime(new Date());
            memberTicket.setTenantCode(orderInfo.getTenantCode());
            memberTicketMapper.insertSelective(memberTicket);


            //用户参与活动累积+1
            MarketActivityMemberExample example = new MarketActivityMemberExample();
            example.createCriteria().andMarketActivityIdEqualTo(marketActivity.getMarketActivityId())
                    .andMemberIdEqualTo(orderInfo.getMemberId());
            List<MarketActivityMember> marketActivityMembers2 = marketActivityMemberService.selectByExample(example);
            MarketActivityMember marketActivityMember1 = marketActivityMembers2.get(0);
            marketActivityMember1.setGainCount(marketActivityMember1.getGainCount() + 1);
            marketActivityMember1.setLastUpdatedTime(new Date());
            marketActivityMemberService.updateByPrimaryKeySelective(marketActivityMember1);
        }

    }
}
